
<template>
  <div class="ask-question-page" :style="'padding-top:'+headHeight+'rpx;'">
 
    <head-back title="提个问题" @goBack="goBack"></head-back>

    <div class="content-box">
      <textarea type="text"  v-model="formData.content" class="write" placeholder="分享你此刻的想法..."></textarea>
      <div class="add-pic">
        <div class="imgItem" v-for="(img,index) in imgPathArr" :key="index">
          <div class="delete" @click="deleteImg(index)">×</div>
          <img class="pic" :src="img" alt>
          <!--<img class="pic" src="https://gg.ewang.com/group2/M00/00/6A/wKgDNV1NHTuAPAQgAADSf2OAdVE139.png!wh_80x80.png">-->
        </div>
        <img class="add-btn" :src="addImgUrl" @click="chosseImg" v-show="isShowBtnUpload" src="../../../../static/image/xxm/add-pic.png">
      </div>
    </div>

    <!-- 添加话题-->
    <div class="add-topic-box border-top">
      <p class="title">艺考百科</p>

      <!--热词-->
      <div class="hot-entry">
        <block v-if="topicData.length > 0">
          <p class="item" v-for="(item,index) in topicData" :key="index" :class="['word'+(index) % 3,item.checkActive ? 'word-active' : '']" @click.stop="selectTopic(item,index)">{{item.title}}</p>
        </block>
      </div>
    </div>

    <!--发布-->
    <div class="btn" @click.sotp="addTopicArt">发布</div>
  </div>
</template>
<script>
    import * as api from '@/utils/api' ;
    const app = getApp();
    import headBack from '@/components/head-back.vue';
    // import albumBox from '@/components/album-box.vue'
  export default {
    onLoad(){
        this.getTopicList();
        this.addImgEvent (); 
    },
    onShow: function () {
        this.formData={
            tag_ids:[],
            user_id:wx.getStorageSync('userInfo').id,
            img_json:[], 
            content:'',
        };
        this.imgPathArr=[];
    },
    data () {
        return {
            headPadding:wx.getStorageSync('headPadding'), 
            headHeight:wx.getStorageSync('headHeight'),
            topicData:[],
            formData:{
                tag_ids:[],
                user_id:wx.getStorageSync('userInfo').id,
                img_json:[], 
                content:'',
            }, 
            imgPathArr:[],
            isShowBtnUpload:true,
            imgLenght: 9, //上传图片的最大数量
            uploadNum:0,//剩余上传张数
            ossSignForm:{
                'domain':'',
                'key': '',
                'policy': '',
                'OSSAccessKeyId':'',
                'Signature': '',
                'success_action_status': '200',
            },
        }
    },
    components:{
      headBack
    },
    methods: {
        goBack(){
            setTimeout(()=>{
                wx.navigateBack({ delta: 1 });
            },300);
        },

        getTopicList(){
            let vm = this;
            api.topicList().then(res => {
            if(res.status == 200) {
              let topicList = [];
              res.data.data.forEach((item,index)=>{
                if(item.id != 2){
                  topicList.push(item)
                }
              })
              vm._data.topicData = topicList;
              }
            
            })
        },
        // //选择话题
        selectTopic(item,index){
            console.log(item);
            if(item.checkActive){
                item.checkActive=!item.checkActive;
                if(this.formData.tag_ids.length>=1){
                    this.formData.tag_ids.forEach((e,eIndex) => {
                        this.formData.tag_ids.splice(eIndex,1);
                    });
                }
            }else{
                if(this.formData.tag_ids.length>=3){
                    wx.showToast({ title: '最多添加三个话题',  })
                }else{
                    this.formData.tag_ids.push(item.id)
                    item.checkActive=true;
                }
            }
            console.log(this.formData.tag_ids)
            this.$forceUpdate();
        },

        //选择图片
        chosseImg(){
            const _this = this;
            let num = 0;
            if(_this.imgPathArr.length < _this.imgLenght){
            num = this.imgLenght - _this.imgPathArr.length;
            wx.chooseImage({
                count: num, //最大图片数量=最大数量-临时路径的数量
                sizeType: ["compressed"],
                sourceType: ["album", "camera"],
                success: res => {
                    const imgPathArr = this.imgPathArr;
                    this.imgPathArr = [];
                    this.imgPathArr = [];
                    this.imgPathArr = imgPathArr.concat(res.tempFilePaths); 
                    _this.updateImg(); 
                }
            });
            }
        },
        //根据临时路径，获取图片base64码
        updateImg(){
            let vm = this;
            //判断是否大于图片最大数量
            if(vm.imgPathArr.length === vm.imgLenght * 1) vm.isShowBtnUpload = false;
            else vm.isShowBtnUpload = true; 
            if(vm.uploadNum+1<=vm.imgPathArr.length&vm.imgPathArr.length>0){ 
                const aliyunFileKey = 'image/'+ new Date().getTime() + Math.floor(Math.random() * 150) + '.png';
                wx.uploadFile({
                    url: vm.ossSignForm.domain,//开发者服务器 url
                    filePath: vm.imgPathArr[vm.uploadNum],//要上传文件资源的路径
                    name: 'file',//必须填file
                    formData: {
                        'OSSAccessKeyId': vm.ossSignForm.OSSAccessKeyId,
                        'policy': vm.ossSignForm.policy,
                        'key': aliyunFileKey, 
                        'success_action_status': '200',
                        'Signature': vm.ossSignForm.Signature,
                        
                    },
                    success: function (res) {
                        // console.log(res);
                        // console.log(vm.ossSignForm.domain+'/'+aliyunFileKey);
                        vm.formData.img_json.push({src:vm.ossSignForm.domain+'/'+aliyunFileKey})
                        vm.uploadNum++;
                        vm.updateImg();
                    },
                    fail: function (err) { 
                        console.log(err);
                    },
                })
            }
        },
        addImgEvent () {
            var vm = this;
            api.fetchOssSign({}).then(res=>{
                if(res.data.code==200){  
                    vm.ossSignForm={
                        domain:res.data.data.domain,
                        'key': res.data.data.key,
                        'policy': res.data.data.policy,
                        'OSSAccessKeyId': res.data.data.OSSAccessKeyId,
                        'Signature': res.data.data.Signature,
                        'success_action_status':'200',
                    }  
                }
            }) 
            
        },
        // 删除图片
        deleteImg(i) { 
            this.imgPathArr.splice(i, 1);
            this.formData.img_json.splice(i, 1);
            if (this.imgPathArr.length < this.imgLenght * 1) {
            this.isShowBtnUpload = null;
            this.isShowBtnUpload = true;
            }
            this.updateImg();
        },
      //发布文章
        addTopicArt(){
            let vm = this;
            if(vm.formData.content==''){
                wx.showModal({
                    showCancel:false,
                    title: '提示',
                    content: '内容不能为空',
                    success (res) {
                        if (res.confirm) {
                        console.log('用户点击确定')
                        } 
                    }
                })
            }else if(vm.formData.tag_ids.length==0){
                wx.showModal({
                    showCancel:false,
                    title: '提示',
                    content: '至少选择一个艺考百科',
                    success (res) {
                        if (res.confirm) {
                        console.log('用户点击确定')
                        } 
                    }
                })
            }else{
                let body={
                    tag_ids:vm.formData.tag_ids,
                    user_id:wx.getStorageSync('userInfo').id,
                    content:vm.formData.content, 
                    img_json:vm.formData.img_json 
                }
                api.addArtItem(body).then(res=>{
                  vm.formData = {
                    tag_ids:[],
                    user_id:wx.getStorageSync('userInfo').id,
                    img_json:[], 
                    content:'',
                  };
                    if(res.data.code==200){
                        wx.showToast({
                            title: '发布成功',
                            icon: 'success',
                            duration: 2000
                        })
                        setTimeout(()=>{
                            wx.navigateBack({
                                delta: 1
                            })
                        },2000)
                    }
                })
            } 
        },
    },
  }
</script>

<style lang="scss" scoped>
  .ask-question-page{
    width:100%;
    height:100%;
    background: #F1F2F7;
    font-size: 32rpx;

    .content-box{
      padding: 32rpx 33rpx;
      width: 100%;
      height: auto;
      background: #ffffff;

      .write{
        width: 100%;
        height: 430rpx;
        min-height: 430rpx;
        max-height: 430rpx;
        color: #999999;
      }

      .add-pic{
        width: 100%;
        height: auto;
        display: flex;
        flex-wrap: wrap;
        /*justify-content: flex-start;*/
        /*align-items: center;*/

        img{
          margin-right: 12rpx;
          width: 124rpx;
          height: 124rpx;
          border-radius: 8rpx;
        }
        .imgItem {
          position: relative;
          margin-top: 12rpx;
        }
        .delete {
          width: 45rpx;
          height: 45rpx;
          line-height: 43rpx;
          background: rgba(0, 0, 0, 0.6);
          color: #fff;
          font-size: 38rpx;
          text-align: center;
          border-radius: 50%;
          position: absolute;
          top: -15rpx;
          right: 5rpx;
          z-index: 12;
        }
      }
    }

    //添加话题
    .add-topic-box{
      padding: 0 33rpx;
      box-sizing: border-box;
      background: #ffffff;

      .title{
        padding: 22rpx 0;
        display:flex;
        align-items:center;
        font-size: 34rpx;
        font-weight: 600;
        color: #0E0E0E;
      }

      //热门词条
      .hot-entry{
        display: inline-flex;
        align-items: center;
        justify-content: flex-start;
        flex-wrap: wrap;
        .word-active{
            padding:22rpx 24rpx;box-shadow: 2rpx 2rpx 2rpx rgb(202, 210, 226);
        }
      }
    }

    //发布
    .btn{
      position: fixed;
      bottom: 0;
      width: 100%;
      height: 88rpx;
      text-align: center;
      line-height: 88rpx;
      font-size: 30rpx;
      color: #ffffff;
      background: linear-gradient(0deg,rgba(77,141,249,1),rgba(86,117,254,1));
      box-shadow: 0 2rpx 7rpx 0 rgba(82,127,252,0.48);
    }
  }

</style>
